package com.example.demo.config;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:龙宝
 * Date:2023-11-09
 * Time:17:10
 */
@Component
public class WebDemo implements WebSocketHandler {
    //保存所有回话
    private static final List<WebSocketSession> sessionList = new ArrayList<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {

        System.out.println("连接成功");
        sessionList.add(session);
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        System.out.println("收到消息：" + message.getPayload().toString());
        sendMsg(message.getPayload().toString());
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println("连接异常");
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        System.out.println("连接关闭");
    }

    @Override
    public boolean supportsPartialMessages() {
        //一次性发送消息 true为可分段发送消息
        return false;
    }

    private void sendMsg(String msg) throws IOException {
        for(WebSocketSession session : sessionList) {
            if(session.isOpen()) {
                session.sendMessage(new TextMessage(msg));
            }
        }
    }
}
